import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { Typography, Card, Row, Col, Statistic, Progress } from 'antd';
import ReactECharts from 'echarts-for-react';
import axios from 'axios';
import moment from 'moment';

const { Title } = Typography;

// 定义企业详情数据的类型（根据后端返回数据）
interface EnterpriseDetails {
  InfoPubDate: string;
  LComNm: string;
  AssetLoss: number;
  CreditLoss: number;
  Revenue: number;
  RiskLevel: string;
  RiskScore: number;
  TotalComprehensiveIncome: number;
  TotalCost: number;
}

const EnterprisePage: React.FC = () => {
  const { name } = useParams<{ name: string }>();
  const [enterprise, setEnterprise] = useState<EnterpriseDetails | null>(null);
  const [trends, setTrends] = useState<EnterpriseDetails[]>([]); // 新增：趋势数据

  useEffect(() => {
    if (name) {
      // 获取企业详情
      axios
        .get<EnterpriseDetails>(`http://localhost:5000/api/enterprise/${encodeURIComponent(name)}`)
        .then((response) => setEnterprise(response.data))
        .catch((error) => console.error('获取企业详情失败:', error));

      // 获取企业趋势数据
      axios
        .get<EnterpriseDetails[]>(`http://localhost:5000/api/enterprise/${encodeURIComponent(name)}/trends`)
        .then((response) => setTrends(response.data))
        .catch((error) => console.error('获取企业趋势数据失败:', error));
    }
  }, [name]);

  // 格式化日期为YYYY-MM-DD
  const formatDate = (dateStr: string) => moment(dateStr).format('YYYY-MM-DD');

  // 配置趋势图的选项
  const createTrendChartOptions = (title: string, dataKey: keyof EnterpriseDetails, yAxisName: string) => ({
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#1890ff',
      },
    },
    tooltip: {
      trigger: 'axis',
    },
    xAxis: {
      type: 'category',
      data: trends.map((item) => formatDate(item.InfoPubDate)),
    },
    yAxis: {
      type: 'value',
      name: yAxisName,
      axisLabel: {
        formatter: '{value} 元',
      },
    },
    series: [
      {
        name: title,
        type: 'line',
        data: trends.map((item) => item[dataKey]),
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#1890ff',
        },
        areaStyle: {
          color: 'rgba(24, 144, 255, 0.2)',
        },
      },
    ],
  });

  return (
    <div
      style={{
        padding: '20px',
        minHeight: '100vh',
        background: 'linear-gradient(to bottom, #f7f7f7, #ffffff)',
        borderRadius: '20px',
        boxShadow: '0 10px 30px rgba(0, 0, 0, 0.1)',
      }}
    >
      <Title
        level={2}
        style={{
          textAlign: 'center',
          marginBottom: '30px',
          color: '#333',
          fontWeight: 'bold',
          textShadow: '1px 1px 2px rgba(0, 0, 0, 0.2)',
        }}
      >
        企业详情
      </Title>

      {enterprise ? (
        <>
          {/* 第一行信息卡片 */}
          <Row gutter={[16, 16]} style={{ marginBottom: '30px' }}>
            <Col span={6}>
              <Card
                bordered={false}
                style={{
                  borderRadius: '15px',
                  background: 'linear-gradient(to bottom, #e6f7ff, #ffffff)',
                  textAlign: 'center',
                  boxShadow: '0 4px 8px rgba(0, 0, 0, 0.05)',
                }}
              >
                <Statistic title="企业名称" value={enterprise.LComNm} />
              </Card>
            </Col>
            <Col span={6}>
              <Card
                bordered={false}
                style={{
                  borderRadius: '15px',
                  background: 'linear-gradient(to bottom, #fffbe6, #ffffff)',
                  textAlign: 'center',
                  boxShadow: '0 4px 8px rgba(0, 0, 0, 0.05)',
                }}
              >
                <Statistic title="最新发布日期" value={formatDate(enterprise.InfoPubDate)} />
              </Card>
            </Col>
            <Col span={6}>
              <Card
                bordered={false}
                style={{
                  borderRadius: '15px',
                  background: 'linear-gradient(to bottom, #fff1f0, #ffffff)',
                  textAlign: 'center',
                  boxShadow: '0 4px 8px rgba(0, 0, 0, 0.05)',
                }}
              >
                <Statistic title="评估等级" value={enterprise.RiskLevel} />
                <Progress
                  percent={Math.abs(enterprise.RiskScore) * 100}
                  size="small"
                  status={enterprise.RiskScore < 0 ? 'active' : 'exception'}
                  strokeColor="#52c41a"
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card
                bordered={false}
                style={{
                  borderRadius: '15px',
                  background: 'linear-gradient(to bottom, #f6ffed, #ffffff)',
                  textAlign: 'center',
                  boxShadow: '0 4px 8px rgba(0, 0, 0, 0.05)',
                }}
              >
                <Statistic title="营业总收入(元)" value={enterprise.Revenue} precision={2} prefix="￥" />
              </Card>
            </Col>
          </Row>

          {/* 第二行信息卡片 */}
          <Row gutter={[16, 16]} style={{ marginBottom: '30px' }}>
            <Col span={6}>
              <Card
                bordered={false}
                style={{
                  borderRadius: '15px',
                  background: '#ffffff',
                  textAlign: 'center',
                  boxShadow: '0 4px 8px rgba(0, 0, 0, 0.05)',
                }}
              >
                <Statistic title="资产减值损失合计(元)" value={enterprise.AssetLoss} precision={2} prefix="￥" />
              </Card>
            </Col>
            <Col span={6}>
              <Card
                bordered={false}
                style={{
                  borderRadius: '15px',
                  background: '#ffffff',
                  textAlign: 'center',
                  boxShadow: '0 4px 8px rgba(0, 0, 0, 0.05)',
                }}
              >
                <Statistic title="信用减值损失合计(元)" value={enterprise.CreditLoss} precision={2} prefix="￥" />
              </Card>
            </Col>
            <Col span={6}>
              <Card
                bordered={false}
                style={{
                  borderRadius: '15px',
                  background: '#ffffff',
                  textAlign: 'center',
                  boxShadow: '0 4px 8px rgba(0, 0, 0, 0.05)',
                }}
              >
                <Statistic
                  title="综合收益总额(元)"
                  value={enterprise.TotalComprehensiveIncome}
                  precision={2}
                  prefix="￥"
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card
                bordered={false}
                style={{
                  borderRadius: '15px',
                  background: '#ffffff',
                  textAlign: 'center',
                  boxShadow: '0 4px 8px rgba(0, 0, 0, 0.05)',
                }}
              >
                <Statistic title="营业总成本(元)" value={enterprise.TotalCost} precision={2} prefix="￥" />
              </Card>
            </Col>
          </Row>

          {/* 趋势图 */}
          <Row gutter={[16, 16]}>
            <Col span={12}>
              <Card title="营业总收入趋势" bordered={false}>
                <ReactECharts
                  option={createTrendChartOptions('营业总收入趋势', 'Revenue', '收入 (元)')}
                  style={{ height: '300px' }}
                />
              </Card>
            </Col>
            <Col span={12}>
              <Card title="资产减值损失趋势" bordered={false}>
                <ReactECharts
                  option={createTrendChartOptions('资产减值损失趋势', 'AssetLoss', '损失 (元)')}
                  style={{ height: '300px' }}
                />
              </Card>
            </Col>
          </Row>
          <Row gutter={[16, 16]}>
            <Col span={12}>
              <Card title="信用减值损失趋势" bordered={false}>
                <ReactECharts
                  option={createTrendChartOptions('信用减值损失趋势', 'CreditLoss', '损失 (元)')}
                  style={{ height: '300px' }}
                />
              </Card>
            </Col>
            <Col span={12}>
              <Card title="综合收益趋势" bordered={false}>
                <ReactECharts
                  option={createTrendChartOptions('综合收益趋势', 'TotalComprehensiveIncome', '收益 (元)')}
                  style={{ height: '300px' }}
                />
              </Card>
            </Col>
          </Row>
        </>
      ) : (
        <p style={{ textAlign: 'center', fontSize: '16px', color: '#999' }}>
          该企业尚未入库系统，暂时无法查阅
        </p>
      )}
    </div>
  );
};

export default EnterprisePage;
